package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceimpl implements ApUserLoginService {
    @Resource
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (dto.getEquipmentId() == null || (StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword()))) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //返回结果
        Map<String, Object> map = new HashMap<>();

        if (StringUtils.isNoneBlank(dto.getPhone()) && StringUtils.isNoneBlank(dto.getPassword())) {
            //根据手机号查询
            ApUser apUserRes = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            //判断数据是否存在
            if (apUserRes == null) {
                throw new CustomException(AppHttpCodeEnum.USER_INEXISTENCE, "您输入的手机号错误");
            }
            //判断用户密码是否正确
            String password = MD5Utils.encodeWithSalt(dto.getPassword(), apUserRes.getSalt());
            if (!password.equals(apUserRes.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.USER_INEXISTENCE, "您输入的密码错误");
            }
            //手机号密码正确颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUserRes.getId()));
            map.put("token", token);
            return ResponseResult.okResult(map);
        } else {
            // 通过设备ID登录的 userId存0
            map.put("token", AppJwtUtil.getToken(Long.valueOf(0)));
            return ResponseResult.okResult(map);
        }

    }
}
